package functions

import (
	"fmt"
	"regexp"

	"github.com/project-flogo/core/data/coerce"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnRegexpMatch{})
	if err != nil {
		panic(err)
	}
}

type fnRegexpMatch struct{}

func (fnRegexpMatch) Name() string {
	return "regexpMatch"
}

func (fnRegexpMatch) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{data.TypeString, data.TypeString}, false
}

func (fnRegexpMatch) Eval(params ...interface{}) (interface{}, error) {
	if len(params) != 2 {
		return nil, fmt.Errorf("wrong number of parameters, expect 2, got %d", len(params))
	}
	str, err := coerce.ToString(params[0])
	if err != nil {
		return nil, err
	}
	pat, err := coerce.ToString(params[1])
	if err != nil {
		return nil, err
	}
	r, err := regexp.Compile(pat)
	if err != nil {
		return nil, err
	}
	return r.FindStringSubmatch(str), nil
}
